package performance

import (
	"fmt"
	"runtime"
	"time"

	"order-validation-api/models"
	"order-validation-api/services"
)

// PerformanceAnalyzer 性能分析器
type PerformanceAnalyzer struct {
	service *services.OrderValidationService
}

// NewPerformanceAnalyzer 创建性能分析器
func NewPerformanceAnalyzer() *PerformanceAnalyzer {
	return &PerformanceAnalyzer{
		service: services.NewOrderValidationService(),
	}
}

// AnalyzeValidationPerformance 分析验证性能
func (pa *PerformanceAnalyzer) AnalyzeValidationPerformance() {
	fmt.Println("=== Order Validation Performance Analysis ===")
	
	// 测试单个订单验证性能
	pa.testSingleOrderPerformance()
	
	// 测试篮子订单验证性能
	pa.testBasketOrderPerformance()
	
	// 测试批量验证性能
	pa.testBatchValidationPerformance()
	
	// 测试内存使用情况
	pa.testMemoryUsage()
}

func (pa *PerformanceAnalyzer) testSingleOrderPerformance() {
	fmt.Println("\n1. Single Order Validation Performance:")
	
	order := &models.Order{
		OrderID:        "QF-20240101-1",
		Type:           models.OrderTypeMarket,
		Currency:       "HKD",
		Symbol:         "0700.HK",
		NotionalAmount: 500,
		Destination:    "DestinationA",
		ClientID:       "A",
		Weight:         1.0,
	}

	iterations := 10000
	start := time.Now()
	
	for i := 0; i < iterations; i++ {
		pa.service.ValidateOrder(order)
	}
	
	duration := time.Since(start)
	avgTime := duration / time.Duration(iterations)
	
	fmt.Printf("   Iterations: %d\n", iterations)
	fmt.Printf("   Total time: %v\n", duration)
	fmt.Printf("   Average time per validation: %v\n", avgTime)
	fmt.Printf("   Validations per second: %.0f\n", float64(iterations)/duration.Seconds())
}

func (pa *PerformanceAnalyzer) testBasketOrderPerformance() {
	fmt.Println("\n2. Basket Order Validation Performance:")
	
	order := &models.Order{
		OrderID:        "QF-20240101-1",
		Type:           models.OrderTypeMarket,
		Currency:       "HKD",
		Symbol:         "BASKET1",
		NotionalAmount: 1000,
		Destination:    "DestinationA",
		ClientID:       "A",
		Weight:         1.0,
		ChildOrders: []models.Order{
			{
				OrderID:        "QF-20240101-2",
				Type:           models.OrderTypeMarket,
				Currency:       "HKD",
				Symbol:         "0700.HK",
				NotionalAmount: 500,
				Destination:    "DestinationA",
				ClientID:       "A",
				Weight:         0.5,
			},
			{
				OrderID:        "QF-20240101-3",
				Type:           models.OrderTypeMarket,
				Currency:       "HKD",
				Symbol:         "0005.HK",
				NotionalAmount: 500,
				Destination:    "DestinationA",
				ClientID:       "A",
				Weight:         0.5,
			},
		},
	}

	iterations := 5000
	start := time.Now()
	
	for i := 0; i < iterations; i++ {
		pa.service.ValidateOrder(order)
	}
	
	duration := time.Since(start)
	avgTime := duration / time.Duration(iterations)
	
	fmt.Printf("   Iterations: %d\n", iterations)
	fmt.Printf("   Total time: %v\n", duration)
	fmt.Printf("   Average time per validation: %v\n", avgTime)
	fmt.Printf("   Validations per second: %.0f\n", float64(iterations)/duration.Seconds())
}

func (pa *PerformanceAnalyzer) testBatchValidationPerformance() {
	fmt.Println("\n3. Batch Validation Performance:")
	
	// 创建100个订单
	orders := make([]*models.Order, 100)
	for i := 0; i < 100; i++ {
		orders[i] = &models.Order{
			OrderID:        fmt.Sprintf("QF-20240101-%d", i+1),
			Type:           models.OrderTypeMarket,
			Currency:       "HKD",
			Symbol:         "0700.HK",
			NotionalAmount: 500,
			Destination:    "DestinationA",
			ClientID:       "A",
			Weight:         1.0,
		}
	}

	iterations := 100
	start := time.Now()
	
	for i := 0; i < iterations; i++ {
		pa.service.ValidateOrderBatch(orders)
	}
	
	duration := time.Since(start)
	totalOrders := iterations * len(orders)
	avgTimePerBatch := duration / time.Duration(iterations)
	avgTimePerOrder := duration / time.Duration(totalOrders)
	
	fmt.Printf("   Batch iterations: %d\n", iterations)
	fmt.Printf("   Orders per batch: %d\n", len(orders))
	fmt.Printf("   Total orders processed: %d\n", totalOrders)
	fmt.Printf("   Total time: %v\n", duration)
	fmt.Printf("   Average time per batch: %v\n", avgTimePerBatch)
	fmt.Printf("   Average time per order: %v\n", avgTimePerOrder)
	fmt.Printf("   Orders per second: %.0f\n", float64(totalOrders)/duration.Seconds())
}

func (pa *PerformanceAnalyzer) testMemoryUsage() {
	fmt.Println("\n4. Memory Usage Analysis:")
	
	var m1, m2 runtime.MemStats
	runtime.GC()
	runtime.ReadMemStats(&m1)
	
	// 创建大量订单进行验证
	orders := make([]*models.Order, 1000)
	for i := 0; i < 1000; i++ {
		orders[i] = &models.Order{
			OrderID:        fmt.Sprintf("QF-20240101-%d", i+1),
			Type:           models.OrderTypeMarket,
			Currency:       "HKD",
			Symbol:         "0700.HK",
			NotionalAmount: 500,
			Destination:    "DestinationA",
			ClientID:       "A",
			Weight:         1.0,
		}
		pa.service.ValidateOrder(orders[i])
	}
	
	runtime.GC()
	runtime.ReadMemStats(&m2)
	
	fmt.Printf("   Memory allocated: %d KB\n", (m2.Alloc-m1.Alloc)/1024)
	fmt.Printf("   Total allocations: %d\n", m2.TotalAlloc-m1.TotalAlloc)
	fmt.Printf("   GC cycles: %d\n", m2.NumGC-m1.NumGC)
}

// GetPerformanceRecommendations 获取性能优化建议
func (pa *PerformanceAnalyzer) GetPerformanceRecommendations() []string {
	return []string{
		"1. 使用对象池(sync.Pool)来重用ValidationResult对象，减少内存分配",
		"2. 实现验证结果缓存，对相同的订单避免重复验证",
		"3. 使用更高效的正则表达式编译和缓存",
		"4. 考虑使用protobuf或其他二进制序列化格式替代JSON",
		"5. 实现连接池来处理数据库连接（如果需要持久化）",
		"6. 使用CPU profiling来识别热点代码路径",
		"7. 考虑使用SIMD指令优化数值计算",
		"8. 实现分层验证，先进行快速检查再进行复杂验证",
		"9. 使用批量处理和流水线技术提高吞吐量",
		"10. 考虑使用内存映射文件来存储大型配置数据",
	}
}